package com.javandad.app.client.fodos;

import java.util.LinkedList;
import java.util.List;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteHandler;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitHandler;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Fodos implements EntryPoint {

	private FodosServiceAsync fsa = GWT.create(FodosService.class);

	@Override
	public void onModuleLoad() {

		this.getSessionInfo();
	}

	public Fodos() {

	}

	private void initGUI(final boolean loggedin) {
		RootPanel rootPanel = RootPanel.get("FodosContainer");

		rootPanel.add(mainPanel);
		mainPanel.setWidth("100%");

		Button btnDelete = new Button("Delete");
		btnDelete.addClickHandler(new ClickHandler() {
		
			public void onClick(ClickEvent event) {
				final List<Long> ids= new LinkedList<Long>();
				for (FodosNode f : FodosNode.fodosList){
				     if (f.simpleCheckBox.getValue()){
				    	 ids.add(Long.parseLong(f.getId()));
				     }
				}
                 fsa.deleteFodos(ids, new AsyncCallback<Boolean>() {

					@Override
					public void onFailure(Throwable caught) {
					}

					@Override
					public void onSuccess(Boolean result) {
						if(result){
							FodosNode.fodosList.clear();
							showFodos(loggedin);
						}
					}
				});
			}
		});
	

		final FormPanel formPanel = new FormPanel();
		formPanel.setMethod(FormPanel.METHOD_POST);
		formPanel.setEncoding(FormPanel.ENCODING_MULTIPART);
		formPanel.setAction("/uploadimage");

		final FileUpload fileUpload = new FileUpload();
		fileUpload.setName("upload");

		formPanel.addSubmitHandler(new SubmitHandler() {

			@Override
			public void onSubmit(SubmitEvent event) {
				if (fileUpload.getFilename() == null
						|| fileUpload.getFilename().equalsIgnoreCase("")) {
					Window.alert("Select a fodo to upload!");
					event.cancel();
				}
			}
		});

		formPanel.addSubmitCompleteHandler(new SubmitCompleteHandler() {

			@Override
			public void onSubmitComplete(SubmitCompleteEvent event) {
				String response = event.getResults();
//				int f = response.indexOf("<pre>") + 5;
//				int l = response.indexOf("</pre>");
//				response = response.substring(f, l);

				table.setWidget(size / col, size % col, new FodosNode(
						"/image?id=" + response, response,fsa));

				size++;
			}
		});

		// fileUpload.setSize("100%", "100%");

		Button btnUploadFodo = new Button("Upload");
		btnUploadFodo.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				if (size < 20)
					formPanel.submit();
				else
					Window.alert("You have reached the maximum!");
			}
		});

		if (loggedin) {
			topPanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT);
			topPanel.add(btnDelete);
			topPanel.add(btnUploadFodo);
			topPanel.add(fileUpload);

			formPanel.add(topPanel);
			mainPanel.add(formPanel);
		}
		col = mainPanel.getOffsetWidth() / 200;
		table = new Grid(20 / col, col);
		
		mainPanel.add(table);

		showFodos(loggedin);

	}

	private void showFodos(boolean loggedin) {
		String dec = view;

		if (loggedin) {
				dec = session.get(1);
		}

		if (dec != null)
			fsa.getFodos(dec, null, new AsyncCallback<List<Long>>() {

				@Override
				public void onFailure(Throwable caught) {
				}

				@Override
				public void onSuccess(List<Long> result) {
					table.clear();
					size = result.size();
					for (int i = 0; i < size; ++i) {

						table.setWidget(i / col, i % col, new FodosNode(
								"/image?id=" + result.get(i), String.valueOf(result.get(i)),fsa));
				    }
				}
			});
	

		

	}

	private void getSessionInfo() {
		fsa.getSessionInfo(new AsyncCallback<List<String>>() {

			@Override
			public void onSuccess(List<String> result) {
				session = result;

				if (session != null && session.get(1) != null) {
					if (view != null && !view.equals(session.get(1)))
						initGUI(false);
					else
						initGUI(true);
				} else {
					if (view != null)
						initGUI(false);
				}
			}

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("Session initialization failed!");
			}
		});
	}

	private VerticalPanel mainPanel = new VerticalPanel();
	private HorizontalPanel topPanel = new HorizontalPanel();
	private Grid table = null;
	private List<String> session = null;
	//private UploadFodosDialogBox uploadBox = new UploadFodosDialogBox();

	final String view = com.google.gwt.user.client.Window.Location
			.getParameter("view");

	private int col;
	private int size;
	
}
